#include "transfermanager.h"
#include "transferprogress.h"

#include <QMessageBox>
#include <cassert>

TransferManager::TransferManager(QWidget *parent) :
	QWidget(parent),
	m_TransferId(0)
{
	setupLayout();
}

void TransferManager::setupLayout()
{
	m_MainLayout = new QVBoxLayout;
	setLayout(m_MainLayout);
}

QString TransferManager::getFileName(int transferId) const
{
	if(!hasTransfer(transferId))
	{
		return "";
	}
	else
	{
		return m_IdToTransInfo[transferId].fileName;
	}
}

QString TransferManager::getSaveFilePath(int transferId) const
{
	if(!hasTransfer(transferId))
	{
		return "";
	}
	else
	{
		return m_IdToTransInfo[transferId].saveFilePath;
	}
}

long long TransferManager::getFileSize(int transferId) const
{
	if(!hasTransfer(transferId))
	{
		return -1;
	}
	else
	{
		return m_IdToTransInfo[transferId].fileSize;
	}
}

long long TransferManager::getTransferredSize(int transferId) const
{
	if(!hasTransfer(transferId))
	{
		return -1;
	}
	else
	{
		return m_IdToTransInfo[transferId].transferId;
	}
}

int TransferManager::addNewTransfer(const QString &fileName, const QString &saveFilePath, long long fileSize)
{
	int transId = ++m_TransferId;

	TransInfo transInfo;
	transInfo.fileName = fileName;
	transInfo.saveFilePath = saveFilePath;
	transInfo.fileSize = fileSize;
	transInfo.transferId = transId;
	transInfo.transferProgress = new TransferProgress(this);
	transInfo.transferProgress->setFileName(fileName);
	transInfo.transferProgress->setFileSize(fileSize);

	m_MainLayout->addWidget(transInfo.transferProgress);
	m_IdToTransInfo.insert(transId, transInfo);
	if(fileSize == 0)
	{
		emit transferComplete(transId);
	}
	return transId;
}

void TransferManager::setTransferredSize(int transferId, long long transferredSize)
{
	if(!hasTransfer(transferId))
	{
		return;
	}

	TransInfo& transInfo = m_IdToTransInfo[transferId];
	transInfo.transferredSize = transferredSize;

//	assert(transferredSize <= transInfo.fileSize);

	transInfo.transferProgress->setTransferredSize(transferredSize);

	if(transferredSize == transInfo.fileSize)
	{
		emit transferComplete(transferId);
	}
}

void TransferManager::onTransferErrorHappend(int transferId, int errorCode)
{
	removeTransfer(transferId);
}

void TransferManager::removeTransfer(int transferId)
{
	if(!hasTransfer(transferId))
	{
		return;
	}

	TransInfo& transInfo = m_IdToTransInfo[transferId];
	delete transInfo.transferProgress;
	m_IdToTransInfo.remove(transferId);
}
